<?php
/* 
 * ebiz front
 * 
 * AjaxController
 * 
 * @author allen
 * 
 */
 
require_once '../app/core/controllers/BaseController.php';
require_once '../app/services/CustomerService.php';
//require_once '../app/views/UtilityView.php';
require_once '../app/core/utils/HttpUtil.class.php';
//require_once '../app/controllers/UtilityController.php';
$path = "../$GLOBALS[local]/"."utility.php";
require_once $path;
//require_once '../app/services/CategoryService.php';
//require_once '../app/services/ProductService.php';
require_once '../app/services/ShoppingCartService.php';
require_once '../app/services/AAService.php';
require_once '../app/services/OrderService.php';
require_once '../app/services/ShippingFeeService.php';
require_once '../app/constants/ConfigConstants.php';

require_once '../app/services/DeliveryService.php';
require_once '../app/services/AreaService.php';
require_once '../app/services/AgentAccountService.php';
require_once '../app/services/QueryService.php';
require_once '../app/services/ProductService.php';

require_once '../app/services/PromotionImplService.php';
require_once '../app/services/VoteService.php';
require_once '../app/services/ApplyGiftService.php';
require_once '../app/services/UserInfoService.php';

class AjaxController extends BaseController {

	/**
	 * ajax validate username uniqueness
	 */
    public function validateusername(){
        $username = strtolower(HttpUtil::getPostString('username'));
        $customerService = new CustomerService();
        $status = $customerService->validateUserName($username);
        $result = array('result' => $status);
        echo json_encode($result);
    }
    
    /**
     * get user by username
     *
     * @author by M.Wang
     */
    public function validateusernameandgetinfo(){
    	if( !AAService::isLogin() ){
    		echo json_encode( array( 'result' => 0 ) );
    		exit;
    	}
    	$username = strtolower(HttpUtil::getPostString('username'));
        $customerService = new CustomerService();
        $result = $customerService->validateUserName($username, true);
        if( !$result )
            echo json_encode( array( 'result' => 0 ) );
        $result['result'] = 1;
        echo json_encode($result);
    }
    
	/**
	 * ajax validate Email uniqueness
	 */
    public function validateemail(){
        $email = strtolower(HttpUtil::getPostString('email'));
        $customerService = new CustomerService();
        $status = $customerService->validateEmail($email);
        $result = array('result' => $status);
        echo json_encode($result);
    }
    
    /**
     * ajax function to change CaptchaImg
     */
    public function changecaptchaimg(){
    	require_once '../app/controllers/ImageController.php';
    	$n = HttpUtil::getGetValue('n');
    	
        $imageController = new ImageController();
        if($n==1){
            $captchaImg = $imageController->indexAction(1);
        } else {
        	$captchaImg = $imageController->indexAction();
        }
        echo $captchaImg;
    }
    
    /**
     * ajax function to validate login
     */
    public function login(){
    	$email = strtolower(HttpUtil::getPostString('email'));
    	$password = md5(HttpUtil::getPostString('password'));
    	$param = array($email, $password);
        $customerService = new CustomerService();
        $status = $customerService->getByEmailAndPassword($param);
        if($status == 1){
            $result = $customerService->getCustomerInfoByEmailAndPassword($param);
            $customerId = $result[0]['id'];
            $status = $result[0]['status'];
            $username = $result[0]['name'];
            $parentId = $result[0]['parent_id'];
            $rank = $result[0]['rank'];
            $campusId = $result[0]['campus_id'];
            $status = $result[0]['status'];
            if($status == 3){
            	$certf = 100;//is Campus Ambassadors,but now is Separation
            }else{
            	$certf = $result[0]['certf'];
            }
            
            AAService::setCustomer($customerId, $certf, $username, $parentId, $rank, $campusId, $status);
            $customerService->updateLastLoginById($customerId);
            $shoppingCartService = new ShoppingcartService();
            $shoppingCartService->combineShoppingCart($customerId); //if login combine cookie info to DB
            //set the https protocol save in cookie
            $token = md5(uniqid(mt_rand(),true));
//            setcookie("token", $token, time() + 60*30, '/', ".".DOMAIN, true); //set the time is 30 minute,but can not run in local include www.i9sell.com
            setcookie("token", $token, time() + 60*30, '/', ".".DOMAIN, false); //false is used in testing environment
            $_SESSION['token'] = $token;
        	echo "success";
        }else{
        	echo "failed";
        }
    }
    
    /**
     * ajax function use in product view 
     * return primary metadata  
     */
    public function generatePrimaryMetadataHtml(){
        $defaultItemId = HttpUtil::getPostString("defaultItemId");
        $productService = new ProductService();
    	$metadataInfo = $productService->getMetadataInfoByItemId($defaultItemId);
        $primaryMetadata = $metadataInfo["short_data"];
        $html = "";
        if(!empty($primaryMetadata)){
            $html .= "<div class='pro_parameter' style='height:auto;'>";
            foreach ($primaryMetadata as $item) {
                $html .= "<div class='p_row_5'>" . $item["attribute"] . "</div>";
                $html .= "<div class='p_row_6'>" . $item["title"] . "</div>";
                $html .= "<div class='clear'></div>";
            }
            $html .= "</div>";
        }
        echo $html;
        
    }
    
    /**
     * ajax function use in product view 
     * return all metadata html
     */
    public function generateAllMetadataHtml(){
        $defaultItemId = HttpUtil::getPostString("defaultItemId");
        $productService = new ProductService();
    	$metadataInfo = $productService->getMetadataInfoByItemId($defaultItemId);
        $data = $metadataInfo["data"];
        $html = "";
        if( !empty($data) ){
            foreach ($data as $item) {
                $metadata = $item["metadatas"];
                if( !empty($metadata) ){
                    //generate the metadata group title
                    $html .=  "<div class='depict_row_2'>";
                    $html .=  "   <ul>";
                    $html .=  "       <li class='style_3'>";
                    if( count($data) != 1 ){
                        $html .=  $item["title"];
                    }
                    $html .=  "       </li>";
                    $html .=  "       <li class='style_2'>";
                    $html .=  "       </li>";
                    $html .=  "   </ul>";
                    $html .=  "</div>";
                    //generate the metadata info
                    foreach ($metadata as $itemData) {
                        $html .= "<div class='depict_row_2'>";
                        $html .= "  <ul>";
                        $html .= "      <li class='style_1'>";
                        $html .= $itemData["attribute"];
                        $html .= "     </li>";
                        $html .= "     <li class='style_2'>";
                        $html .= $itemData["title"];
                        $html .= "     </li>";
                        $html .= "  </ul>";
                        $html .= "</div>";
                    }
                }
            }
        }
        echo $html;
    }
    
    /**
     * ajax function use in product view 
     * return item inventory Prompt Info html
     */
    public function getItemInventoryInfoHtml(){
    	$html = "";
    	$itemId = HttpUtil::getPostString("itemId");
    	$quantity = HttpUtil::getPostString("quantity");
    	$productService = new ProductService();
    	$pItemInfo = $productService->getItemInfoByItemId($itemId);
    	$inventory = $pItemInfo[0]["inventory"];
    	$salePrice = $pItemInfo[0]["sale_price"];
    	if( $inventory < $quantity || $inventory <= 0 || $salePrice <= 0 ){
    		$html .= "<div style='text-align:center;'> <strong style='color: red;font-size:16px;'>  </strong> </div>";
    	}
    	echo $html;
    }
    
    /**
     * when submit the opinion generate the point html code
     */
    public function getopinionpointhtml(){
    	$productId = HttpUtil::getPostString("productId");
    	$voteService = new VoteService();
    	$avgPoint = $voteService->getAvgStarPointView($productId);
    	echo $avgPoint;
    }
    
    /**
     * generate the pagination code of opinion part
     */
    public function getopinionhtml(){
    	$productId = HttpUtil::getPostString("productId");
    	$currentPage = HttpUtil::getPostString("currentPage");
    	$voteService = new VoteService();
    	$dealCommon = $voteService->getStarPointForm($productId, $currentPage);
    	echo $dealCommon;
    }
    
    public function getOpinionPaginationHtml(){
    	$itemsPerPage = $GLOBALS["config"]['items_per_page'];
        $productId = HttpUtil::getPostString("productId");
        $currentPage = HttpUtil::getPostString("currentPage");
        $voteService = new VoteService();
        $opinionAllNum = $voteService->getCommentsNumberByProductId($productId);
    	$pager = new Pager();
        $pager->setJavascriptFunction("javascript:ProductContent.ajaxOpinionPaginate");
        $headerPaginate = $pager->paginate($currentPage, $opinionAllNum, "", $itemsPerPage);
        echo $headerPaginate;
    }
    
    /**
     * function start
     * 
     * ajax function use in product view 
     * return current query html
     */
    public function getQueryHtml(){
    	$queryAllHtml = "";
//    	$itemsPerPage = $GLOBALS["config"]['items_per_page'];
    	$itemsPerPage = 5;
    	$currentDiv = HttpUtil::getPostString("currentDiv");
    	$productId = HttpUtil::getPostString("productId");
    	$currentPage = HttpUtil::getPostString("currentPage");
    	$currentType = $currentDiv - 1;
    	if($currentType == 0){
    		$currentType = "";
    	}
        $queryService = new QueryService();
        $queryAll = $queryService->getQueryByProductId($productId, ($currentPage - 1) * $itemsPerPage, $itemsPerPage, $currentType);
        $queryAllNumArray = $queryService->getQueryByProductId($productId, ($currentPage - 1) * $itemsPerPage, $itemsPerPage, $currentType, true);
        $queryAllNum = $queryAllNumArray[0]["ROWS"];
        $pager = new Pager();
        $pager->setJavascriptFunction("javascript:ProductContent.ajaxPaginate");
        $headerPaginate = $pager->paginate($currentPage, $queryAllNum, "", $itemsPerPage);
        $queryAllHtml .= "<div id='ady_1'>";
        foreach ($queryAll as $item) {
            $queryAllHtml .= "<div class='ady_body'><div class='ady_arraign'>";
            $queryAllHtml .= $item["query_content"];
            $queryAllHtml .= "</div><div class='ady_row_1'>  用户名： ";
            $queryAllHtml .= $item["user_name"];
            $queryAllHtml .= "  时间： ";
            $queryAllHtml .= $item["query_created"];
            $queryAllHtml .= "  咨询类型： ";
            $queryAllHtml .= $item["query_type"];
            $queryAllHtml .= "</div><div class='ady_reply'>";
            $queryAllHtml .= $item["reply_content"];
            $queryAllHtml .= "</div><div class='ady_row_2'>";
            $queryAllHtml .= $item["admin_name"];
            $queryAllHtml .= "  回复于   ";
            $queryAllHtml .= $item["reply_modified"];
            $queryAllHtml .= "</div>  </div>  ";
        }
        $queryAllHtml .= "<div class='p2_page'>".$headerPaginate."</div>";
        $queryAllHtml .= "</div>";
        echo $queryAllHtml;
    }
    
    /**
     * ajax function use in product view 
     * generate the consult info 
     */
    public function queryAllHtml(){
    	$pid = HttpUtil::getPostString("pid");
    	$config = $GLOBALS["config"];
//    	$itemsPerPage = $config['items_per_page'];
    	$itemsPerPage = 5;
    	$pager = new Pager();
    	$queryService = new QueryService();
    	//consult info and consult number
        $queryAll = $queryService->getQueryByProductId($pid, 0, $itemsPerPage);
        $queryAllNumInfo = $queryService->getQueryByProductId($pid, 0, $itemsPerPage, "", true);
        $queryAllNum = $queryAllNumInfo[0]["ROWS"];
        
        $queryGoods = $queryService->getQueryByProductId($pid, 0, $itemsPerPage, 1);
        $queryGoodsNumInfo = $queryService->getQueryByProductId($pid, 0, $itemsPerPage, 1, true);
        $queryGoodsNum = $queryGoodsNumInfo[0]["ROWS"];
        
        $queryDistribute = $queryService->getQueryByProductId($pid, 0, $itemsPerPage, 2);
        $queryDistributeNumInfo = $queryService->getQueryByProductId($pid, 0, $itemsPerPage, 2, true);
        $queryDistributeNum = $queryDistributeNumInfo[0]["ROWS"];
        
        $queryPayment = $queryService->getQueryByProductId($pid, 0, $itemsPerPage, 3);
        $queryPaymentNumInfo = $queryService->getQueryByProductId($pid, 0, $itemsPerPage, 3, true);
        $queryPaymentNum = $queryPaymentNumInfo[0]["ROWS"];
        
        $queryCampuses = $queryService->getQueryByProductId($pid, 0, $itemsPerPage, 4);
        $queryCampusesNumInfo = $queryService->getQueryByProductId($pid, 0, $itemsPerPage, 4, true);
        $queryCampusesNum = $queryCampusesNumInfo[0]["ROWS"];
        
        $queryMaintain = $queryService->getQueryByProductId($pid, 0, $itemsPerPage, 5);
        $queryMaintainNumInfo = $queryService->getQueryByProductId($pid, 0, $itemsPerPage, 5, true);
        $queryMaintainNum = $queryMaintainNumInfo[0]["ROWS"];
        
        $queryAllHtml = self::generateEachHtml($queryAll, $queryAllNum, $pager, 1);
        $queryGoodsHtml = self::generateEachHtml($queryGoods, $queryGoodsNum, $pager, 2);
        $queryDistributeHtml = self::generateEachHtml($queryDistribute, $queryDistributeNum, $pager, 3);
        $queryPaymentHtml = self::generateEachHtml($queryPayment, $queryPaymentNum, $pager, 4);
        $queryCampusesHtml = self::generateEachHtml($queryCampuses, $queryCampusesNum, $pager, 5);
        $queryMaintainHtml = self::generateEachHtml($queryMaintain, $queryMaintainNum, $pager, 6);
        
        $allHtml = $queryAllHtml.$queryGoodsHtml.$queryDistributeHtml.$queryPaymentHtml.$queryCampusesHtml.$queryMaintainHtml;
        echo $allHtml;
    }
    
    /**
     * generate the html code
     */
    private function generateEachHtml($queryAll, $queryAllNum, $pager, $currentDiv){
        //get the page size from config table
//        $itemsPerPage = $GLOBALS["config"]['items_per_page'];
        $itemsPerPage = 5;
        $pager->setJavascriptFunction("javascript:ProductContent.ajaxPaginate");
        $headerPaginate = $pager->paginate(1, $queryAllNum, "", $itemsPerPage);
        $queryAllHtml = "<div id='ady_" . $currentDiv . "'>";
        foreach ($queryAll as $item) {
            $queryAllHtml .= "<div class='ady_body'>";
            $queryAllHtml .= "  <div class='ady_arraign'>";
            $queryAllHtml .= $item["query_content"];
            $queryAllHtml .= "  </div>";
            $queryAllHtml .= "  <div class='ady_row_1'>  用户名： ";
            $queryAllHtml .= $item["user_name"];
            $queryAllHtml .= "  时间： ";
            $queryAllHtml .= $item["query_created"];
            $queryAllHtml .= "  咨询类型： ";
            $queryAllHtml .= $item["query_type"];
            $queryAllHtml .= "  </div>";
            if( !empty($item["reply_content"]) && !empty($item["reply_modified"]) ){
	            $queryAllHtml .= "  <div class='ady_reply'>";
	            $queryAllHtml .= $item["reply_content"];
	            $queryAllHtml .= "  </div>";
	            $queryAllHtml .= "  <div class='ady_row_2'>";
	//            $queryAllHtml .= $item["admin_name"];
	            $queryAllHtml .= "  回复于   ";
	            $queryAllHtml .= $item["reply_modified"];
	            $queryAllHtml .= "  </div>  ";
            }
            $queryAllHtml .= "</div>";
        }
        $queryAllHtml .= "<div class='p2_page' >".$headerPaginate."</div>";
        $queryAllHtml .= "</div>";
        return $queryAllHtml;
    }
    
    /**
     * generate the number
     */
    public function queryNumberHtml(){
    	$result = array();
    	$pid = HttpUtil::getPostString("pid");
        $config = $GLOBALS["config"];
//        $itemsPerPage = $config['items_per_page'];
        $itemsPerPage = 5;
        $queryService = new QueryService();
        //consult info and consult number
        $queryAllNumInfo = $queryService->getQueryByProductId($pid, 0, $itemsPerPage, "", true);
        $queryAllNum = $queryAllNumInfo[0]["ROWS"];
        
        $queryGoodsNumInfo = $queryService->getQueryByProductId($pid, 0, $itemsPerPage, 1, true);
        $queryGoodsNum = $queryGoodsNumInfo[0]["ROWS"];
        
        $queryDistributeNumInfo = $queryService->getQueryByProductId($pid, 0, $itemsPerPage, 2, true);
        $queryDistributeNum = $queryDistributeNumInfo[0]["ROWS"];
        
        $queryPaymentNumInfo = $queryService->getQueryByProductId($pid, 0, $itemsPerPage, 3, true);
        $queryPaymentNum = $queryPaymentNumInfo[0]["ROWS"];
        
        $queryCampusesNumInfo = $queryService->getQueryByProductId($pid, 0, $itemsPerPage, 4, true);
        $queryCampusesNum = $queryCampusesNumInfo[0]["ROWS"];
        
        $queryMaintainNumInfo = $queryService->getQueryByProductId($pid, 0, $itemsPerPage, 5, true);
        $queryMaintainNum = $queryMaintainNumInfo[0]["ROWS"];
        
        $pageInfo = array("queryAllNum" => $queryAllNum, 
                          "queryGoodsNum" => $queryGoodsNum, 
                          "queryDistributeNum" => $queryDistributeNum, 
                          "queryPaymentNum" => $queryPaymentNum, 
                          "queryCampusesNum" => $queryCampusesNum, 
                          "queryMaintainNum" => $queryMaintainNum 
                          );
//        $result = array( "pageNum" => $pageInfo );
        echo json_encode($pageInfo);
    }
    
    /**
     * function end
     */
    
    /**
     * ajax function use in product view 
     * submit the user query
     */
    public function submitQuery(){
    	$userId = HttpUtil::getPostString("userId");
        $productId = HttpUtil::getPostString("productId");
        $queryContent = HttpUtil::getPostString("queryContent");
        $queryType = HttpUtil::getPostString("queryType");
        if(!empty($userId)){
            $queryService = new QueryService();
            $queryService->insertQuery($productId, $queryType, $userId, 1, $queryContent);
            echo "success";
        }else{
            echo "fail";
        }        
        
        
    }
    
    /**
     * ajax function use in shopping cart view 
     * judge the user bought quantity if less than inventity of DB,or the item already delete 
     * return item info to show user
     */
    public function getitemqtyinfo(){
        $itemIds = HttpUtil::getPostString("itemIds");
        $quantitys = HttpUtil::getPostString("quantitys");
        $scIds = HttpUtil::getPostString("scIds");
        $itemIdArray = explode(",", $itemIds);
        $quantityArray = explode(",", $quantitys);
        $scIdArray = explode(",", $scIds);
        $shoppingcartService = new ShoppingcartService();
        $result = $shoppingcartService->getItemQtyInfo($itemIdArray, $quantityArray, $scIdArray);
        $html = $shoppingcartService->showHtmlInfo($result);
        echo $html;
    }
    
 /**
  * Validate if old password is right when one intents to modify password.
  *
  */   
    public function validateoldpassword(){
    	$oldPassword = md5(HttpUtil::getPostString('oldPassword'));
    	
    	$AAService = new AAService();
    	$customerId = $AAService->getCustomer();
    	
    	$customerService = new CustomerService();
    	$result = $customerService->validateOldPassword($oldPassword,$customerId);
     
        echo json_encode($result);
    	
    }
    
    /**
     * checkout page
     * ajax function to add new address 
     */
	public function addnewaddress(){
		$userId = AAService::getCustomer();
		$addUserName = HttpUtil::getPostString("addUserName");
		$province = HttpUtil::getPostString("province");
		$city = HttpUtil::getPostString("city");
		$county = HttpUtil::getPostString("county");
		$addOtherAddress = HttpUtil::getPostString("addOtherAddress");
		$addPhone = HttpUtil::getPostString("addPhone");
		$addMobileTelephone = HttpUtil::getPostString("addMobileTelephone");
		$addEmail = HttpUtil::getPostString("addEmail");
		$param = array($userId, $addUserName, $province, $city, $county, $addOtherAddress, $addPhone, $addMobileTelephone, $addEmail);
		$deliveryService = new DeliveryService();
		$areaService = new AreaService();
		$addressId = $deliveryService->saveDelivery($param);
		$provinceName = $areaService->getAreaById($province);
        $cityName = $areaService->getAreaById($city);
        $districtName = $areaService->getAreaById($county);
		/*$result = array("id" => $addressId,
		                "addUserName" => $addUserName,
		                "province" => $provinceName,
		                "city" => $cityName,
		                "country" => $districtName,
		                "addOtherAddress" => $addOtherAddress,
		                "addMobileTelephone" => $addMobileTelephone);
        echo json_encode($result);
        */
        $result = "";
        $result .= "<input type='radio' name='address' value='".$addressId."' checked='checked' style='float:left;margin-top:10px;' onclick='CheckOut.useTheAddressInfo();' />";
//        $result .= "<input type='radio' name='address' value='".$addressId."'  style='float:left;' />";
        $result .= "<div style='margin-top:10px;' id='address_".$addressId."'>";
        $result .= "<span id='province_".$addressId."'>".$provinceName[0]["title"]."</span> ";
        $result .= "<span id='cityName_".$addressId."'>".$cityName[0]["title"]."</span> ";
        $result .= "<span id='districtName_".$addressId."'>".$districtName[0]["title"]."</span> ";
        $result .= "<span id='otherAddress_".$addressId."'>".$addOtherAddress."</span> ";
        $result .= " ( 收货人：";        
        $result .= "<span id='userName_".$addressId."'>".$addUserName."</span>, ";        
        $result .= "<span id='mobileTelephone_".$addressId."'>".$addMobileTelephone."</span> )";        
//        $result .= $provinceName[0]["title"]." ".$cityName[0]["title"]." ".$districtName[0]["title"]." ".$addOtherAddress." (收货人： $addUserName ，  $addMobileTelephone )";
        $result .= "</div>";
        $result .= "<div class='clear'></div>";
        $result .= "<input type='hidden' id='phone_".$addressId."' value='".$addPhone."' />";
        $result .= "<input type='hidden' id='email_".$addressId."' value='".$addEmail."' />";
        $result .= "<input type='hidden' id='province_".$addressId."' value='".$province."' />";
		echo $result; 
	}

    /**
     * checkout page
     * count the address number if generate 5 then not to add new
     */
    public function countaddressnum(){
    	$userId = AAService::getCustomer();
    	$deliveryService = new DeliveryService();
    	$addressNum = $deliveryService->getAddressNumByUserId($userId);
    	echo $addressNum[0]["count(*)"];
    }
    
    /**
     * checkout page
     * show the campuses of the province
     */
    public function generatecampuses(){
        $html = "";
    	$areaDictId = HttpUtil::getPostString("areaDictId");
    	$noInOrder = HttpUtil::getPostString("noInOrder");
    	$areaService = new AreaService();
    	if($noInOrder){
    		$campuses = $areaService->getCampusByDictId($areaDictId,0);
    	}else {
    	    $campuses = $areaService->getCampusByDictId($areaDictId);
    	}
    	foreach ($campuses as $name) {
    		$areaName = $name["area_name"];
    		$id = $name["id"];
//    		$html .="<li><a href='javascript:CheckOut.viewArea(\"" . $areaName . "\" , \"" . $id . "\" );'>".$areaName."</a></li>";
    		$html .='<li><a href="javascript:CheckOut.viewArea(\'' . $areaName . '\' , \'' . $id . '\' );">'.$areaName.'</a></li>';
    	}
    	echo $html;
    }
    
    /**
     * checkout page
     * show the ambassador info by campusesId
     */
    public function generateambassador(){
    	$html = "";
    	$campusesId = HttpUtil::getPostString("campusesId");
    	$customerService = new CustomerService();
    	$result = $customerService->getCustomerByCampusesId($campusesId);
    	$isShow = 0;//$isShow = 0 then do not show the selectDeputy div;
    	foreach ($result as $item) {
            if(!empty($item['team_name'])){
            	$isShow = 1;
            }
    	}
    	
    	if($isShow == 1){
	    	$html .= "<span style='margin-left:30px;'>选择离你最近的代理人：</span>";
	    	$html .= "<span style='margin-left:50px;'>";
	    	for($i = 0; $i < count($result); $i++) {
//	    		if(!empty($item['team_name'])){
	    		if(!empty($result[$i]['team_name'])){
	    			if($i == 0){
	    				$html .= "<span style='margin-left:10px;'>";
	                    $html .= "<input type='radio' value='".$result[$i]['id']."' name='userId' checked='checked' />".$result[$i]['team_name'];
	                    $html .= "<input type='hidden' value='".$result[$i]['team_name']."' id='teamName_".$result[$i]['id']."' />";
	                    $html .= "</span>";
	    			}else{
	    				$html .= "<span style='margin-left:10px;'>";
	                    $html .= "<input type='radio' value='".$result[$i]['id']."' name='userId' />".$result[$i]['team_name'];
	                    $html .= "<input type='hidden' value='".$result[$i]['team_name']."' id='teamName_".$result[$i]['id']."' />";
	                    $html .= "</span>";
	    			}
			        
	    		}
	    	}
	    	$html .= "</span>";
	    	$html .= "";
    	}
    	echo $html;
    }
    
    /**
     * ajax function when use the coupon code
     */
    public function getcouponinfo(){
		$couponTotal = HttpUtil::getPostString("couponTotal");  //$couponTotal is Merchandise Total - Discount value
		$couponCode = HttpUtil::getPostString("couponCode");
		$itemIds = HttpUtil::getPostString("itemIds");
		$quantitys = HttpUtil::getPostString("quantitys");
		$salePrices = HttpUtil::getPostString("salePrices");
		$firstPromotion = HttpUtil::getPostString("usedPromotion") == "true" ? true:false;
		$stackable = HttpUtil::getPostString("stackable") == "true" ? true:false;
		$totalPrices = HttpUtil::getPostString("totalPrices");
		$itemIdArray = explode(",", $itemIds);
		$quantityTempArray = explode(",", $quantitys);
		$salePricesTempArray = explode(",", $salePrices);
		$totalPricesTempArray = explode(",", $totalPrices);
		$quantityArray = array();
		$salePricesArray = array();
		$totalPricesArray = array();
		for($i = 0; $i < count($itemIdArray); $i++){
		    $quantityArray[$itemIdArray[$i]] = $quantityTempArray[$i];
		    $salePricesArray[$itemIdArray[$i]] = $salePricesTempArray[$i];
		    $totalPricesArray[$itemIdArray[$i]] = $totalPricesTempArray[$i] / $quantityTempArray[$i];
		}
		$userId = AAService::getCustomer();
		$promotionImplService = new PromotionImplService();
		$couponInfo = $promotionImplService->impl($couponTotal, $itemIdArray, $quantityArray, $totalPricesArray, $userId, $firstPromotion, $stackable, $couponCode);
		echo json_encode($couponInfo);
    } 
    
    /**
     * ajax function count the tax when config table enable_tax = 1 && product_items table taxable = 1 && city_taxes table the city tax_rate is not 0 
     */
    public function counttax(){
        $config = $GLOBALS["config"];
        $enableTax = $config['enable_tax'];//1 is taxable , 0 is not use tax
        $cityName = HttpUtil::getPostString("cityName");
        $itemIds = HttpUtil::getPostString("itemIds");
        $totals = HttpUtil::getPostString("totals");
        $stateName = HttpUtil::getPostString("stateName");
        if($enableTax == 1){
            $orderService = new OrderService();
            $tax = $orderService->countTax($cityName, $itemIds, $totals, $stateName);
            echo $tax;//format in JS
        }else{
            echo 0;
        }
    } 
    
    /**
     * ajax to validate the qty from productItems and shoppingCart table for checkout page
     */
    public function getitemqtyinfoforcheckout(){
        $customerId = AAService::getCustomer();
        $itemIds = HttpUtil::getPostString("itemIds");
        $quantitys = HttpUtil::getPostString("quantitys");
        $quantityArray = explode(",", $quantitys);
        $orderService = new OrderService();
        $shoppingcartService = new ShoppingcartService();
        $result = $orderService->getItemQtyInfoForCheckOut($itemIds, $quantityArray, $customerId);
        $html = $shoppingcartService->showHtmlInfo($result); 
        echo $html;
    }
    
    /**
     * ajax to validate the sale price from productItems for checkout page
     */
    public function getitemsalepriceforcheckout(){
    	$salePriceResultArray = array();
    	$itemIds = HttpUtil::getPostString("itemIds");
    	$salePrices = HttpUtil::getPostString("salePrices");
    	$itemIdArray = explode(",", $itemIds);
    	$salePriceArray = explode(",", $salePrices);
    	for($i = 0; $i < count($itemIdArray); $i++) {
    		$salePriceResultArray[$itemIdArray[$i]] = $salePriceArray[$i];
    	}
    	
    	$orderService = new OrderService();
        $shoppingcartService = new ShoppingcartService();
        $result = $orderService->getItemSalePriceForCheckout($salePriceResultArray);
        $html = $shoppingcartService->showPriceHtmlInfo($result); 
        echo $html;
    }
    
    /**
     * ajax function use in checkout page
     * judje if current province is xinjiang or xizang then SF shipping payment not to select
     * add function to return price of shipping method
     */
    public function judgeExceptionProvince(){
    	$addressId = HttpUtil::getPostString("addressId");
    	$deliveryService = new DeliveryService();
    	$deliveryInfo = $deliveryService->getDeliveryById($addressId);
    	$provinceId = $deliveryInfo[0]["address_1"];
    	if($provinceId == 2916 || $provinceId == 3306){
    		echo "xjxz";
    	}else{
    		echo "normal";
    	}
    }
    
    /**
     * ajax function use in checkout page
     * count the shipping fee by province 
     */
    public function countShipFee(){
    	$itemAllTotal = 0;
        $totals = HttpUtil::getPostString("totals");
        $totalTempArray = explode(",", $totals);
        foreach ($totalTempArray as $itemTotal) {
        	$itemAllTotal += $itemTotal;
        }
    	$promotionImplService = new PromotionImplService();
        //get which shipping method is free shipping
        $freeShippingMethod = intval( $promotionImplService->processFreeShipping($itemAllTotal) );//return if current promotion can freeshipping,return ship method
        
    	$result = array();
    	$shipRule = HttpUtil::getPostString("shipRule");
    	$addressId = HttpUtil::getPostString("addressId");
    	$deliveryService = new DeliveryService();
    	$deliveryInfo = $deliveryService->getDeliveryById($addressId);
        $provinceId = $deliveryInfo[0]["address_1"];
        if($shipRule == 1){
	        if( $freeShippingMethod == 1 ){//use free shipping promotion 
	            $result["normal"] = 0;
	        }else{//do not use promotion
	        	$result["normal"] = Order::$normalWeightFee;
	        }
    		
    		if($provinceId == 3306 || $provinceId == 2916 || $freeShippingMethod == 5 ){
    			$result["SF"] = 0;
    		}else{
    			$result["SF"] = Order::$SFWeightFee;
    		}
    		if( $freeShippingMethod == 2 ){
    			$result["EMS"] = 0;
    		}else{
    			$result["EMS"] = Order::$EMSWeightFee;
    		}
    	}else{
   	        $orderService = new OrderService();
   	        $result = $orderService->countShipFeeByWeight($provinceId, $freeShippingMethod);//which shipping type is free shipping
    	}
    	echo json_encode($result);
        
    }
    
    
    
    
    
    /**
     * ajax to save the vote point by choice star
     */
    public function savestarchoice(){
    	$int_userid = 0;
    	if(AAService::isLogin()){
    		$int_userid = AAService::getCustomer();
    	}
        $int_productid = HttpUtil::getPostString('product_id');
        $float_point = HttpUtil::getPostString('starpoint');
        if( empty( $float_point ) )
            $float_point = 0;
        if( $float_point && $float_point < 1 )
            $float_point = 1;
        if( $float_point > 5 )
            $float_point = 5;
        $str_comments = HttpUtil::getPostString('content');
        require_once '../app/services/VoteService.php';
        $voteService = new VoteService();
        $arr_param = array(
            'user_id' => $int_userid,
            'product_id' => $int_productid,
            'point' => $float_point,
            'content' => $str_comments
        );
        echo $voteService->saveComments($arr_param);
    }
    
    public function getProductPageComments(){
        $int_productid = HttpUtil::getPostString('product_id');
        require_once '../app/services/VoteService.php';
        $voteService = new VoteService();
        echo $voteService->getCommentsView( $int_productid );
    }
    
    public function checkusagebalance(){
        $userId = AAService::getCustomer();
        $price = trim(HttpUtil::getPostString ('price'));
        $agentAccountSercive = new AgentAccountSercive();
        $accountAgentTotal = $agentAccountSercive->getAccountAgentTotalByUserId($userId);  
        if(floatval($price)>$accountAgentTotal['usage_balance']||$accountAgentTotal['usage_balance']<=0){
            $result= '1';
        }else{
            $result = '0';
        }
        echo json_encode(array('result'=>$result));
        exit;
    }    

    public function categorysearch($arr_param){
        array_shift($arr_param);
        array_shift($arr_param);
        array_shift($arr_param);
        require_once '../app/controllers/CategoryController.php';
        $categoryController = new CategoryController();
        echo $categoryController->search($arr_param,true);
        exit;
    }
    
    /**
     * 没有购买不能发表评论
     */
    public function iscanopinion(){
    	$productService = new ProductService();
    	$userId = HttpUtil::getPostString ('userId');
    	$pid = HttpUtil::getPostString ('productId');
    	$result = $productService->isCanOpinion($userId, $pid);
    	if($result){//可以发表评论
    		echo "success";
    	}else{
    		echo "";
    	}
    }
    
    /**
     * 所有评论页面分页ajax方法
     */
    public function getCommentHtml(){
    	$itemsPerPage = $GLOBALS["config"]['items_per_page'];
    	$currentPage = HttpUtil::getPostString('currentPage');
    	$int_productid = HttpUtil::getPostString('productId');
    	$voteService = new VoteService();
    	$result = $voteService->getAllCommentsByProductId( $int_productid, ($currentPage - 1) * $itemsPerPage, $itemsPerPage );
    	//得到该商品评价的数目
        $opinionItemNumber = $voteService->getOpinionNumber($int_productid);
        //生成分页html
        $pager = new Pager();
        $pager->setJavascriptFunction("javascript:ProductAllOpinion.ajaxPaginate");
        $headerPaginate = $pager->paginate($currentPage, $opinionItemNumber, "", $itemsPerPage);
    	require_once '../app/views/ProductAllOpinionPaginateView.php';
    }
    
    /**
     * 判断用户的晋级积分与兑换积分是否允许兑换该礼品
     */
    public function canExchangeGift(){
    	$userId = AAService::getCustomer();
    	$giftId = HttpUtil::getPostString('giftId');
    	$minAcPoints = HttpUtil::getPostString('minAcPoints');
    	$exhaustPoints = HttpUtil::getPostString('exhaustPoints');
    	$customerService = new CustomerService();
    	$userInfo = $customerService->getCustomerById($userId);
    	$points_buyer = $userInfo[0]["points_buyer"];
    	$points_buyer_total = $userInfo[0]["points_buyer_total"];
    	if( !(AAService::isLogin() && AAService::isActive()) ){
    	   echo "active";
    	   exit;
    	}
    	if($points_buyer_total >= $minAcPoints && $points_buyer >= $exhaustPoints){//用户符合兑换的晋级积分条件并且用户的兑换积分大于礼品的兑换积分
//    		$new_points_buyer = $points_buyer - $exhaustPoints;
//    		$customerService->updateBuyerPointByCid($userId, $new_points_buyer);
            echo "success";
            exit;
    	}else{
    		echo "point";
            exit;
    	}
    }
    
    /**
     * 生成兑换礼品的分页html
     */
    public function getExchangeHtml(){
        $itemsPerPage = $GLOBALS["config"]['items_per_page'];
        $currentPage = HttpUtil::getPostString('currentPage');
        $applyGiftService = new ApplyGiftService();
        $giftProductInfo = $applyGiftService->getGiftProductInfo($currentPage);
        $queryAllNum = $applyGiftService->getAllNum();
        //生成分页html
        $pager = new Pager();
        $pager->setJavascriptFunction("javascript:ExchangeContent.ajaxPaginate");
        $itemsPerPage = $GLOBALS["config"]['items_per_page'];//akimimi set is 20
        $headerPaginate = $pager->paginate($currentPage, $queryAllNum, "", $itemsPerPage);
        
        require_once '../app/views/ExchangeCenterPaginateView.php';
    }
    
    /**
     * 判断用户的晋级积分与兑换积分是否允许兑换抵用券
     */
    public function canExchangePromotion(){
        $userId = AAService::getCustomer();
        $minAcPoints = HttpUtil::getPostString('minAcPoints');
        $exhaustPoints = HttpUtil::getPostString('exhaustPoints');
        $customerService = new CustomerService();
        $userInfo = $customerService->getCustomerById($userId);
        $points_buyer = $userInfo[0]["points_buyer"];
        $points_buyer_total = $userInfo[0]["points_buyer_total"];
        if($points_buyer_total >= $minAcPoints && $points_buyer >= $exhaustPoints){//用户符合兑换的晋级积分条件并且用户的兑换积分大于礼品的兑换积分
            echo "success";
        }else{
            echo "false";
        }
    }
    
    /**
     * 生成兑换信息列表的分页html
     */
    public function getExchangeListHtml(){
    	$itemsPerPage = $GLOBALS["config"]['items_per_page'];
        $currentPage = HttpUtil::getPostString('currentPage');
        $applyGiftService = new ApplyGiftService();
        $exchangeInfo = $applyGiftService->showExchangeInfo($currentPage);
        
        //生成分页html
        $pager = new Pager();
        $queryAllNum = $applyGiftService->getAllNumber();
        $pager->setJavascriptFunction("javascript:ExchangeContent.ajaxGiftPaginate");
        $headerPaginate = $pager->paginate($currentPage, $queryAllNum, "", $itemsPerPage);
        require_once '../app/views/ExchangeGiftListPaginateView.php';
    	
    }
    
    /**
     * 添加到wishlist
     */
    public function addtowishlist(){
    	if(!AAService::isLogin()){
    	   echo "false";
    	   exit;
    	}
        $userId = AAService::getCustomer();
    	$itemId = HttpUtil::getPostString('itemId');
        $userInfoService = new UserInfoService();
        $userInfos = $userInfoService->getUserWishlistInfoByUserId(0);
        $isExist = false;
        
        foreach ($userInfos as $userInfo) {
        	if($userInfo["pi_id"] == $itemId){
                $isExist = true;
        	}
        }
        if(!$isExist){
            $param = array(
				            'customer_id' => $userId,
				            'product_item_id' => $itemId,
				            'created' => date('Y-m-d H:i:s'),
				            'modified' => date('Y-m-d H:i:s')
	        );
	        $userInfoService->saveUserWishlistInfo($param);
        }
        echo "true";
        exit;
    }
    
    /**
     * wishlist分页
     */
    public function getWishlistHtml(){
        $itemsPerPage = $GLOBALS["config"]['items_per_page'];
        $currentPage = HttpUtil::getPostString('currentPage');
        $userInfoService = new UserInfoService();
        $wishlistInfo = $userInfoService->getUserWishlistInfoByUserId($currentPage);
        //生成分页html
        $wishlistAllNumber = $userInfoService->getWishlistAllNumber();
        $pager = new Pager();
        $pager->setJavascriptFunction("javascript:WishlistContent.ajaxWishlistPaginate");
        $headerPaginate = $pager->paginate($currentPage, $wishlistAllNumber, "", $itemsPerPage);
        require_once '../app/views/WishlistPaginateView.php';
    }
    
    /**
     * 删除wishlist中的产品
     */
    public function deliteminfo(){
    	$userInfoService = new UserInfoService();
    	$cwid = HttpUtil::getPostString('cwid');
    	$userInfoService->delWishlistItem($cwid);
    	
        $itemsPerPage = $GLOBALS["config"]['items_per_page'];
        $currentPage = 1;
        $wishlistInfo = $userInfoService->getUserWishlistInfoByUserId($currentPage);
        //生成分页html
        $wishlistAllNumber = $userInfoService->getWishlistAllNumber();
        $pager = new Pager();
        $pager->setJavascriptFunction("javascript:WishlistContent.ajaxWishlistPaginate");
        $headerPaginate = $pager->paginate($currentPage, $wishlistAllNumber, "", $itemsPerPage);
        require_once '../app/views/WishlistPaginateView.php';
    }
    
    /**
     * 编辑comment
     */
    public function updatecomment(){
    	$cwid = HttpUtil::getPostString('cwid');
    	$comment = HttpUtil::getPostString('comment');
        $userInfoService = new UserInfoService();
        $userInfoService->updateWishlistComment($cwid, $comment);
    	echo $comment;
    }
    
    /**
     * 添加wishlist中的item到shoppingcart中
     */
    public function addwishlistitemtocart(){
        $productItemId = HttpUtil::getPostString('productItemId');
        $salePrice = HttpUtil::getPostString('salePrice');
        $productId = HttpUtil::getPostString('productId');
        $quantity = 1;
        $shoppingCartService = new ShoppingcartService();
        $customerId = AAService::getCustomer();  //get user id
        $param = array($productId, $productItemId, $customerId, $quantity, $salePrice);
        if($shoppingCartService->shoppingCartIsExist($productItemId, $customerId)){ //this item is exist , only update the quantity
            $shoppingCartService->addQuantityByCidItemid($customerId, $productItemId, $quantity);
        }else{  //this item is not exist , add a new one
            $shoppingCartService->addShoppingCart($param);  //insert into value to shopping_carts table
        }
    }
    

}



